package fragments;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import beans.CabinetInfoBean;
import beans.InitCabinetNumberBean;
import beans.InitCabinetNumberParam;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.ObjectSaveUtil;
import utils.ToastUtil;

/**
 * Created by Administrator on 2018/5/9.
 */

public class CabinetNumberFragment extends BaseFragment {
    @BindView(R.id.tv_scm_number_fragment_first)
    TextView tv_1;
    @BindView(R.id.tv_scm_number_fragment_second)
    TextView tv_2;
    @BindView(R.id.tv_scm_number_fragment_third)
    TextView tv_3;
    @BindView(R.id.tv_scm_number_fragment_fourth)
    TextView tv_4;
    @BindView(R.id.tv_scm_number_fragment_fifth)
    TextView tv_5;
    Unbinder unbinder;
    private ImageView ivFirst, ivSecond, ivThird, ivFourth, ivFifth;
    private ImageView iv_1, iv_2, iv_3, iv_4, iv_5;
    private TextView tvComplete;
    private int selectCabinetCode;
    //用于判断上一次选中的是哪个柜子
    private int beforeSelect = 0;
    private MyHandler allHandler;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor edit;
    private String address;
    //用于判断tvComplete是否可以点击
    private boolean isClickable;
    private List<Integer> list = new ArrayList<>();
    private Map<String, Integer> saveMap = new HashMap<>();

    @Override
    protected void onHandleMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.SCM_NUMBER_CLOSE_DOOR:
                //单片机的地址
                address = (String) msg.obj;
                ToastUtil.showToastlog(mContext,address);
                isClickable = true;
                tvComplete.setBackground(getResources().getDrawable(R.drawable.terminal_text_selector));
                break;
        }
    }

    @Nullable

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_cabinet_number, null);
        unbinder = ButterKnife.bind(this, view);
        initView(view);
        setListener();
        return view;
    }

    @Override
    public void setListener() {
        ivFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_1.setVisibility(View.VISIBLE);
                selectCabinetClick(1);
            }
        });
        ivSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_2.setVisibility(View.VISIBLE);
                selectCabinetClick(2);
            }
        });
        ivThird.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_3.setVisibility(View.VISIBLE);
                selectCabinetClick(3);
            }
        });
        ivFourth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_4.setVisibility(View.VISIBLE);
                selectCabinetClick(4);
            }
        });
        ivFifth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_5.setVisibility(View.VISIBLE);
                selectCabinetClick(5);
            }
        });
        tvComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isClickable) {
                    getCabinetInfo();
                } else {
                    ToastUtil.showToast(getContext(), "请选择柜子,并关门,然后点击完成");
                }
            }
        });
    }

    private void getCabinetInfo() {
        GetRetrofit.getInstance().getCabinetInfo(NetAddress.token, NetAddress.machineCode, "select * from CabinetInfo where CabinetCode = '" + address + "'").subscribeOn(Schedulers.io()).groupBy(new Func1<ArrayList<CabinetInfoBean>, Boolean>() {
            @Override
            public Boolean call(ArrayList<CabinetInfoBean> cabinetInfoBeen) {
                return cabinetInfoBeen == null ? false : cabinetInfoBeen.size() != 0;
            }
        }).flatMap(new Func1<GroupedObservable<Boolean, ArrayList<CabinetInfoBean>>, Observable<CabinetInfoBean>>() {
            @Override
            public Observable<CabinetInfoBean> call(GroupedObservable<Boolean, ArrayList<CabinetInfoBean>> booleanArrayListGroupedObservable) {
                if (booleanArrayListGroupedObservable.getKey()) {
                    return booleanArrayListGroupedObservable.map(new Func1<ArrayList<CabinetInfoBean>, CabinetInfoBean>() {
                        @Override
                        public CabinetInfoBean call(ArrayList<CabinetInfoBean> cabinetInfoBeen) {
                            return cabinetInfoBeen.get(0);
                        }
                    });
                } else {
                    List<InitCabinetNumberParam> list = new ArrayList<InitCabinetNumberParam>();
                    InitCabinetNumberParam bean = new InitCabinetNumberParam();
                    bean.setCabinetCode(address);
                    bean.setOnlyNumber(String.valueOf(selectCabinetCode));
                    bean.setTerminalId(NetAddress.terminalInfoId);
                    list.add(bean);
                    //第一次编码
                    initCabinetNumber(list);
                    return null;
                }
            }
        }).map(new Func1<CabinetInfoBean, Integer>() {
            @Override
            public Integer call(CabinetInfoBean cabinetInfoBean) {
                return cabinetInfoBean.getID();
            }
        }).subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                if (integer > 0) {
                    List<InitCabinetNumberParam> list = new ArrayList<InitCabinetNumberParam>();
                    InitCabinetNumberParam bean = new InitCabinetNumberParam();
                    bean.setLogicNumber(String.valueOf(selectCabinetCode));
                    bean.setCabinetInfoId(String.valueOf(integer));
                    list.add(bean);
                    //非第一次编码
                    initCabinetNumber(list);
                } else {
                    //第一次编码
                    List<InitCabinetNumberParam> list = new ArrayList<InitCabinetNumberParam>();
                    InitCabinetNumberParam bean = new InitCabinetNumberParam();
                    bean.setCabinetCode(address);
                    bean.setOnlyNumber(String.valueOf(selectCabinetCode));
                    bean.setTerminalId(NetAddress.terminalInfoId);
                    list.add(bean);
                    initCabinetNumber(list);
                }
            }
        }, new MyAction1());

    }

    private void initCabinetNumber(List<InitCabinetNumberParam> list) {
        GetRetrofit.getInstance().initCabinetNumber(NetAddress.token, NetAddress.machineCode, list).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<InitCabinetNumberBean>() {
            @Override
            public void call(InitCabinetNumberBean initCabinetNumberBean) {
                for (int i = 1; i < 6; i++) {
                    if (address.equals(sharedPreferences.getString(Constants.ADDRESS + i, ""))) {
                        edit = sharedPreferences.edit();
                        edit.putString(Constants.ADDRESS + i, "");
                        edit.commit();
                    }
                }
                saveCabinetAddress();
            }
        }, new MyAction1());
    }

    private void saveCabinetAddress() {
        Map<String, Integer> map = new HashMap<>();
        Map<String, Integer> readMap = (Map<String, Integer>) ObjectSaveUtil.readObject(mContext, Constants.CABINET_NUMBER, Constants.CABINET_NUMBER);

        if (readMap != null && readMap.size() != 0) {
            map = readMap;
        }

        map.put(address, selectCabinetCode);
        ObjectSaveUtil.saveObject(mContext, map, Constants.CABINET_NUMBER, Constants.CABINET_NUMBER);


        setNumberTextColor(map);

        // 存储柜子对应的单片机地址
        edit = sharedPreferences.edit();
        edit.putString(Constants.ADDRESS + selectCabinetCode, address);
        edit.commit();
        ToastUtil.showToast(getContext(), "编码完成");
        tvComplete.setBackground(getResources().getDrawable(R.drawable.unselect_shape));
        isClickable = false;
    }

    public void selectCabinetClick(int i) {
        selectCabinetCode = i;
        if (selectCabinetCode != beforeSelect) {
            if (beforeSelect == 1) {
                iv_1.setVisibility(View.GONE);
            } else if (beforeSelect == 2) {
                iv_2.setVisibility(View.GONE);
            } else if (beforeSelect == 3) {
                iv_3.setVisibility(View.GONE);
            } else if (beforeSelect == 4) {
                iv_4.setVisibility(View.GONE);
            } else if (beforeSelect == 5) {
                iv_5.setVisibility(View.GONE);
            }
            beforeSelect = selectCabinetCode;
        }

        if (isClickable) {
            tvComplete.setBackground(getResources().getDrawable(R.drawable.unselect_shape));
            isClickable = false;
        }

        Message message = allHandler.obtainMessage();
        message.obj = selectCabinetCode;
        message.what = HandlerConstant.BEGIN_SCM_NUMBER;
        allHandler.sendMessage(message);

    }

    private void initView(View contentView) {

        ivFirst = (ImageView) contentView.findViewById(R.id.iv_scm_number_fragment_first);
        ivSecond = (ImageView) contentView.findViewById(R.id.iv_scm_number_fragment_second);
        ivThird = (ImageView) contentView.findViewById(R.id.iv_scm_number_fragment_third);
        ivFourth = (ImageView) contentView.findViewById(R.id.iv_scm_number_fragment_fourth);
        ivFifth = (ImageView) contentView.findViewById(R.id.iv_scm_number_fragment_fifth);

        iv_1 = (ImageView) contentView.findViewById(R.id.iv_1);
        iv_2 = (ImageView) contentView.findViewById(R.id.iv_2);
        iv_3 = (ImageView) contentView.findViewById(R.id.iv_3);
        iv_4 = (ImageView) contentView.findViewById(R.id.iv_4);
        iv_5 = (ImageView) contentView.findViewById(R.id.iv_5);

        tvComplete = (TextView) contentView.findViewById(R.id.tv_scm_number_fragment_complete);
        allHandler = SingletonClass.getSingleton(MyHandler.class);
//        retrofit = GetEnterInterface.getRetrofit(getContext());
        sharedPreferences = ActivityUtil.getSharedPreferences(getContext());

        Map<String, Integer> readMap = (Map<String, Integer>) ObjectSaveUtil.readObject(mContext, Constants.CABINET_NUMBER, Constants.CABINET_NUMBER);

        if (readMap != null && readMap.size() != 0) {
            setNumberTextColor(readMap);
        }

    }

    private void setNumberTextColor(Map<String, Integer> map) {
        Set setMap = saveMap.entrySet();
        Iterator mapInterator = setMap.iterator();

        while (mapInterator.hasNext()) {
            Map.Entry mapentry = (Map.Entry) mapInterator.next();
            int number = (int) mapentry.getValue();
            String key = (String) mapentry.getKey();
            if (map.containsKey(key)) {
                if (1 == number) {
                    tv_1.setTextColor(getResources().getColor(R.color.search_fragment_top));
                }
                if (2 == number) {
                    tv_2.setTextColor(getResources().getColor(R.color.search_fragment_top));
                }
                if (3 == number) {
                    tv_3.setTextColor(getResources().getColor(R.color.search_fragment_top));
                }
                if (4 == number) {
                    tv_4.setTextColor(getResources().getColor(R.color.search_fragment_top));
                }
                if (5 == number) {
                    tv_5.setTextColor(getResources().getColor(R.color.search_fragment_top));
                }
            }
        }

        saveMap.clear();

        Set set = map.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry mapentry = (Map.Entry) iterator.next();
            Integer number = (Integer) mapentry.getValue();
            String key = (String) mapentry.getKey();
            if (1 == number) {
                saveMap.put(key, number);
                tv_1.setTextColor(getResources().getColor(R.color.terminal_color));
            } else if (2 == number) {
                saveMap.put(key, number);
                tv_2.setTextColor(getResources().getColor(R.color.terminal_color));
            } else if (3 == number) {
                saveMap.put(key, number);
                tv_3.setTextColor(getResources().getColor(R.color.terminal_color));
            } else if (4 == number) {
                saveMap.put(key, number);
                tv_4.setTextColor(getResources().getColor(R.color.terminal_color));
            } else if (5 == number) {
                saveMap.put(key, number);
                tv_5.setTextColor(getResources().getColor(R.color.terminal_color));
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        allHandler.sendEmptyMessage(HandlerConstant.NO_BEGIN_SCM_NUMBER);
    }
}
